<template>
  <div class="return-material-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 生产退料</p>
            <h2 class="breadcrumb-heading">生产退料</h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item>生产退料</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="search-card">
      <div class="search-card__header">
        <h3>高级筛选</h3>
        <span>支持关键字、物料与日期组合查询</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="退料单号">
          <el-input
            v-model="searchForm.returnMaterialCode"
            placeholder="请输入退料单号"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="物料名称/编号">
          <el-input
            v-model="searchForm.materialKeyword"
            placeholder="请输入物料名称或编号"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Box /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="工单名称">
          <el-input
            v-model="searchForm.workOrderName"
            placeholder="请输入工单名称"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="请选择退料时间">
          <el-date-picker
            v-model="searchForm.returnMaterialDate"
            type="date"
            placeholder="请选择退料时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
            class="search-input"
            :prefix-icon="Calendar"
          />
        </el-form-item>
        <el-form-item label="退料状态">
          <el-select
            v-model="searchForm.stats"
            placeholder="请选择退料状态"
            clearable
            class="search-input"
          >
            <el-option label="待退料" :value="0" />
            <el-option label="已退料" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-actions">
          <el-button :icon="RefreshLeft" @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            :loading="loading"
            :icon="Search"
            @click="handleSearch"
            >查询</el-button
          >
          <el-dropdown>
            <el-button type="info">
              更多
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleExport"
                  >导出全部</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-header__info">
          <h3 class="table-title">
            <el-icon class="table-title-icon"><Box /></el-icon>
            生产退料列表
          </h3>
          <p class="table-subtitle">
            共 <strong>{{ pagination.totalCount }}</strong> 条数据，当前第
            <strong>{{ pagination.pageIndex }}</strong
            >/<strong>{{ totalPages }}</strong> 页
          </p>
          <el-tag
            v-if="multipleSelection.length > 0"
            type="info"
            class="selection-tag"
          >
            已选择 {{ multipleSelection.length }} 项
          </el-tag>
        </div>
        <div class="table-header__actions">
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            class="action-btn add-btn"
            >新增退料单</el-button
          >
          <el-button
            type="danger"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
            class="action-btn batch-delete-btn"
            >批量删除</el-button
          >
          <el-button
            type="info"
            :icon="Download"
            :loading="exportLoading"
            @click="handleExport"
            class="action-btn export-btn"
            >导出</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        class="modern-table"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          width="60"
          :index="getIndex"
        />
        <el-table-column
          prop="returnMaterialCode"
          label="退料单号"
          min-width="150"
        >
          <template #default="{ row }">
            <el-link type="primary" :underline="false" @click="handleView(row)">
              {{ row.returnMaterialCode || "-" }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnMaterialDate"
          label="退料日期"
          min-width="120"
        >
          <template #default="{ row }">
            <span class="table-date">{{
              formatDate(row.returnMaterialDate)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退料状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getStatusMeta(row.stats).tagType"
              effect="light"
              class="status-tag"
              round
            >
              {{ getStatusMeta(row.stats).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="workOrderName"
          label="工单名称"
          min-width="150"
        />
        <el-table-column prop="workOrderCode" label="工单号" min-width="150" />
        <el-table-column prop="taskName" label="任务名称" min-width="150" />
        <el-table-column prop="taskCode" label="任务编号" min-width="150" />
        <el-table-column prop="processName" label="工序名称" min-width="150" />
        <el-table-column prop="returner" label="退料人" min-width="120" />
        <el-table-column prop="materialName" label="物料名称" min-width="150" />
        <el-table-column prop="materialCode" label="物料编号" min-width="150" />
        <el-table-column prop="specModel" label="规格型号" min-width="120" />
        <el-table-column prop="unit" label="单位" min-width="80">
          <template #default="{ row }">
            {{ row.unit || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currentReturnQuantity"
          label="退料数量"
          min-width="110"
          align="right"
        >
          <template #default="{ row }">
            {{ row.currentReturnQuantity ?? "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="pickBatchNo" label="批次号" min-width="120">
          <template #default="{ row }">
            {{ row.pickBatchNo || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="returnReason" label="退料原因" min-width="150">
          <template #default="{ row }">
            {{ row.returnReason || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库名称" min-width="130">
          <template #default="{ row }">
            {{ row.warehouseName || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.remark || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button
                v-if="row.stats === 0"
                type="success"
                link
                size="small"
                @click="handleReturn(row)"
                :loading="executingReturnId === row.id"
                :disabled="executingReturnId === row.id"
                class="table-action-btn return-btn"
                >退料</el-button
              >
              <el-button
                type="primary"
                link
                size="small"
                @click="handleEdit(row)"
                class="table-action-btn edit-btn"
                >编辑</el-button
              >
              <el-button
                type="danger"
                link
                size="small"
                @click="handleDelete(row)"
                class="table-action-btn delete-btn"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <div class="empty-icon-wrapper">
              <el-icon class="empty-icon"><Box /></el-icon>
            </div>
            <p class="empty-text">暂无生产退料数据</p>
            <p class="empty-hint">
              您可以点击上方"新增退料单"按钮创建新的生产退料单
            </p>
            <el-button
              type="primary"
              :icon="Plus"
              @click="handleAdd"
              class="empty-action-btn"
              >立即创建退料单</el-button
            >
          </div>
        </template>
      </el-table>
      <div class="table-pagination">
        <div class="pagination-wrapper">
          <div class="pagination-info">
            <span class="pagination-text"
              >共 <strong>{{ pagination.totalCount }}</strong> 条记录</span
            >
          </div>
          <div class="pagination-controls">
            <el-button
              size="small"
              @click="gotoFirst"
              :disabled="pagination.pageIndex === 1"
              class="pagination-btn"
              >首页</el-button
            >
            <el-button
              size="small"
              @click="gotoPrev"
              :disabled="pagination.pageIndex === 1"
              class="pagination-btn"
              >上一页</el-button
            >
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 30, 50]"
              background
              layout="prev, pager, next"
              :total="pagination.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="pagination-component"
            />
            <el-button
              size="small"
              @click="gotoNext"
              :disabled="pagination.pageIndex >= totalPages"
              class="pagination-btn"
              >下一页</el-button
            >
            <el-button
              size="small"
              @click="gotoLast"
              :disabled="pagination.pageIndex >= totalPages"
              class="pagination-btn"
              >尾页</el-button
            >
            <el-select
              v-model="pagination.pageSize"
              size="small"
              class="page-size-select"
              @change="handleSizeChange"
            >
              <el-option label="10条/页" :value="10" />
              <el-option label="20条/页" :value="20" />
              <el-option label="30条/页" :value="30" />
              <el-option label="50条/页" :value="50" />
            </el-select>
            <span class="pagination-jumper">前往</span>
            <el-input
              v-model="jumpPage"
              size="small"
              class="jump-input"
              @keyup.enter="handleJumpPage"
            />
            <span class="pagination-jumper">页</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Search,
  Calendar,
  Plus,
  Download,
  RefreshLeft,
  ArrowDown,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";

const router = useRouter();

type StatusTagType = "" | "success" | "warning" | "info" | "danger";

interface StatusMeta {
  label: string;
  tagType: StatusTagType;
}

const STATUS_META: Record<number, StatusMeta> = {
  0: { label: "待退料", tagType: "warning" },
  1: { label: "已退料", tagType: "success" },
};

const normalizeStatus = (value: unknown): number => {
  const parsed = Number(value);
  return Number.isNaN(parsed) ? 0 : parsed;
};

const getStatusMeta = (status?: number | null): StatusMeta => {
  const normalized =
    typeof status === "number" ? status : normalizeStatus(status);
  return STATUS_META[normalized] ?? { label: "未知状态", tagType: "info" };
};

// 接口定义
interface ProduceReturnMaterialDto {
  id: number;
  returnMaterialCode: string;
  returnMaterialName: string;
  returnMaterialDate?: string;
  returner: string;
  workOrderName: string;
  workOrderCode: string;
  taskName: string;
  taskCode: string;
  processRoute: string;
  processName: string;
  remark?: string;
  stats: number;
  materialName: string;
  materialCode: string;
  specModel: string;
  unit?: string;
  pickBatchNo?: string;
  currentReturnQuantity: number;
  returnReason?: string;
  productionDate?: string;
  expireDate?: string;
  warehouseName?: string;
  warehouseAreaName?: string;
  warehouseLocationName?: string;
  itemRemark?: string;
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

onMounted(() => {
  loadReturnMaterialList();
});

const tableData = ref<ProduceReturnMaterialDto[]>([]);
const loading = ref(false);
const multipleSelection = ref<ProduceReturnMaterialDto[]>([]);
const jumpPage = ref(1);
const executingReturnId = ref<number | null>(null);

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  returnMaterialCode: "",
  materialKeyword: "",
  workOrderName: "",
  returnMaterialDate: "" as string | null,
  stats: null as number | null,
});

// 序号计算
const getIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1;
};

// 日期格式化
const formatDate = (date: string | Date | null | undefined) => {
  if (!date) return "-";
  return moment(date).format("YYYY-MM-DD");
};

// 总页数
const totalPages = computed(() =>
  Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize))
);

// 加载生产退料列表
const loadReturnMaterialList = () => {
  loading.value = true;
  const params: any = {
    PageIndex: pagination.pageIndex,
    PageSize: pagination.pageSize,
  };

  if (searchForm.returnMaterialCode) {
    params.ReturnMaterialCode = searchForm.returnMaterialCode.trim();
  }

  if (searchForm.materialKeyword) {
    params.MaterialKeyword = searchForm.materialKeyword.trim();
  }

  if (searchForm.workOrderName) {
    params.WorkOrderName = searchForm.workOrderName.trim();
  }

  if (searchForm.returnMaterialDate) {
    params.ReturnMaterialDate = searchForm.returnMaterialDate;
  }

  if (searchForm.stats !== null && searchForm.stats !== undefined) {
    params.Stats = searchForm.stats;
  }

  https.Reads.get("/Warehouse/ProduceReturnMaterialList", { params })
    .then((res: any) => {
      console.log("=== 生产退料列表响应 ===");
      console.log("完整响应:", res);
      console.log("res.data:", res.data);

      const responseData = res.data;

      if (responseData) {
        const code = responseData.code ?? responseData.Code;
        let dataList: any[] = [];
        let total = 0;
        let pageCount = 0;

        // 优先使用 data 字段（camelCase）
        if (responseData.data !== undefined) {
          dataList = Array.isArray(responseData.data) ? responseData.data : [];
          total = responseData.totalCount ?? 0;
          pageCount = responseData.pageCount ?? 0;
        }
        // 如果没有 data，尝试 Data 字段（PascalCase）
        else if (responseData.Data !== undefined) {
          dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
          total = responseData.TotalCount ?? 0;
          pageCount = responseData.PageCount ?? 0;
        }

        console.log("解析结果:", {
          code,
          dataListLength: dataList.length,
          total,
          pageCount,
          firstItem: dataList[0],
        });

        // 只有当 code 明确是 -1（错误）时才显示错误
        if (code === -1) {
          console.error("响应失败，code:", code);
          const msg =
            responseData.msg ?? responseData.Msg ?? "获取生产退料列表失败";
          ElMessage.error(msg);
          tableData.value = [];
          pagination.totalCount = 0;
        } else {
          // code 为 0、1 或 undefined 时，都尝试显示数据
          tableData.value = dataList.map((item: ProduceReturnMaterialDto) => {
            const statusValue = normalizeStatus(
              (item as any).stats ?? (item as any).Stats ?? item.stats
            );
            return {
              ...item,
              stats: statusValue,
            };
          });
          pagination.totalCount = total;
          pagination.pageCount = pageCount;
          jumpPage.value = pagination.pageIndex;
          console.log("数据加载成功（code:", code, "），共", total, "条");
        }
      } else {
        console.error("响应数据为空");
        ElMessage.error("获取生产退料列表失败：响应数据为空");
        tableData.value = [];
        pagination.totalCount = 0;
      }
    })
    .catch((error: any) => {
      console.error("=== 加载生产退料列表失败 ===");
      console.error("错误对象:", error);
      console.error("错误响应:", error.response);
      console.error("错误数据:", error.response?.data);
      console.error("错误消息:", error.message);

      const errorMsg =
        error?.response?.data?.msg ??
        error?.response?.data?.Msg ??
        error?.message ??
        "获取生产退料列表失败，请稍后重试";
      ElMessage.error(errorMsg);
      tableData.value = [];
      pagination.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询
const handleSearch = () => {
  pagination.pageIndex = 1;
  loadReturnMaterialList();
};

// 重置
const handleReset = () => {
  searchForm.returnMaterialCode = "";
  searchForm.materialKeyword = "";
  searchForm.workOrderName = "";
  searchForm.returnMaterialDate = null;
  searchForm.stats = null;
  handleSearch();
};

// 每页条数改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  loadReturnMaterialList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  loadReturnMaterialList();
};

// 首页
const gotoFirst = () => {
  if (pagination.pageIndex !== 1) {
    pagination.pageIndex = 1;
    loadReturnMaterialList();
  }
};

// 上一页
const gotoPrev = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex -= 1;
    loadReturnMaterialList();
  }
};

// 下一页
const gotoNext = () => {
  if (pagination.pageIndex < totalPages.value) {
    pagination.pageIndex += 1;
    loadReturnMaterialList();
  }
};

// 尾页
const gotoLast = () => {
  if (pagination.pageIndex !== totalPages.value) {
    pagination.pageIndex = totalPages.value;
    loadReturnMaterialList();
  }
};

// 跳转到指定页
const handleJumpPage = () => {
  const page = Number(jumpPage.value);
  if (page >= 1 && page <= totalPages.value) {
    pagination.pageIndex = page;
    loadReturnMaterialList();
  } else {
    ElMessage.warning(`请输入1-${totalPages.value}之间的页码`);
    jumpPage.value = pagination.pageIndex;
  }
};

// 新增
const handleAdd = () => {
  router.push("/ReturnMaterialAdd");
};

// 查看
const handleView = (row: ProduceReturnMaterialDto) => {
  ElMessage.info("查看功能待实现");
  // TODO: 跳转到详情页面或打开详情对话框
};

// 退料
const handleReturn = async (row: ProduceReturnMaterialDto) => {
  if (row.stats !== 0) {
    ElMessage.warning("该生产退料单已退料，无需重复操作");
    return;
  }
  try {
    await ElMessageBox.confirm("确认要执行退料操作吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    });

    executingReturnId.value = row.id;
    const payload = { id: row.id };
    const res = await https.Writes.put(
      "/Warehouse/ProduceReturnMaterialExecute",
      payload
    );
    const responseData = res?.data ?? {};
    const code = responseData.code ?? responseData.Code;
    const msg = responseData.msg ?? responseData.Msg ?? "执行生产退料成功";

    if (code === 1) {
      ElMessage.success(msg);
      loadReturnMaterialList();
    } else {
      throw new Error(msg || "执行生产退料失败");
    }
  } catch (error: any) {
    if (error === "cancel") {
      ElMessage.info("已取消退料操作");
      return;
    }
    console.error("执行退料失败:", error);
    const errMessage =
      error?.response?.data?.msg ??
      error?.response?.data?.Msg ??
      error?.message ??
      "执行生产退料失败，请稍后重试";
    ElMessage.error(errMessage);
  } finally {
    executingReturnId.value = null;
  }
};

// 编辑
const handleEdit = (row: ProduceReturnMaterialDto) => {
  // 根据主表ID分组，获取该主表的所有明细
  const mainId = row.id;
  const allDetails = tableData.value.filter((item) => item.id === mainId);

  // 构建主表数据（取第一条，因为主表信息相同）
  const mainData = {
    id: row.id,
    returnMaterialCode: row.returnMaterialCode,
    returnMaterialName: row.returnMaterialName || "",
    returnMaterialDate: row.returnMaterialDate || null,
    returner: row.returner || "",
    workOrderName: row.workOrderName || "",
    workOrderCode: row.workOrderCode || "",
    taskName: row.taskName || "",
    taskCode: row.taskCode || "",
    processRoute: row.processRoute || "",
    processName: row.processName || "",
    remark: row.remark || "",
    detail: allDetails.map((item) => ({
      id: null,
      returnMaterialMainId: item.id,
      materialName: item.materialName || "",
      materialCode: item.materialCode || "",
      specModel: item.specModel || "",
      unit: item.unit || "",
      pickBatchNo: item.pickBatchNo || "",
      currentReturnQuantity: item.currentReturnQuantity || 0,
      returnReason: item.returnReason || "",
      productionDate: item.productionDate || null,
      expireDate: item.expireDate || null,
      warehouseName: item.warehouseName || "",
      warehouseAreaName: item.warehouseAreaName || "",
      warehouseLocationName: item.warehouseLocationName || "",
      itemRemark: item.itemRemark || "",
    })),
  };

  // 跳转到新增页面，通过路由参数传递数据
  router.push({
    path: "/ReturnMaterialAdd",
    query: {
      editId: mainId.toString(),
      editData: encodeURIComponent(JSON.stringify(mainData)),
    },
  });
};

// 删除
const handleDelete = (row: ProduceReturnMaterialDto) => {
  ElMessageBox.confirm("确认要删除该生产退料单吗？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      https.Writes.put("/Warehouse/ProduceReturnMaterialDelete", { id: row.id })
        .then((res: any) => {
          const responseData = res?.data ?? {};
          const code = responseData.code ?? responseData.Code;
          const msg = responseData.msg ?? responseData.Msg ?? "删除成功";

          if (code === 1) {
            ElMessage.success(msg);
            loadReturnMaterialList();
          } else {
            ElMessage.error(msg || "删除失败");
          }
        })
        .catch((error: any) => {
          console.error("删除失败:", error);
          const errMessage =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "删除失败，请稍后重试";
          ElMessage.error(errMessage);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const handleSelectionChange = (val: ProduceReturnMaterialDto[]) => {
  multipleSelection.value = val;
};

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的生产退料单！");
    return;
  }

  const ids = multipleSelection.value.map((x) => x.id);

  ElMessageBox.confirm(
    `确认要批量删除选中的${multipleSelection.value.length}条生产退料单吗？`,
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      https.Writes.delete("/Warehouse/ProduceReturnMaterialDeletes", {
        data: { Ids: ids },
      })
        .then((res: any) => {
          const responseData = res?.data ?? {};
          const code = responseData.code ?? responseData.Code;
          const msg = responseData.msg ?? responseData.Msg ?? "批量删除成功";

          if (code === 1) {
            ElMessage.success(msg);
            loadReturnMaterialList();
          } else {
            ElMessage.error(msg || "批量删除失败");
          }
        })
        .catch((error: any) => {
          console.error("批量删除失败:", error);
          const errMessage =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "批量删除失败，请稍后重试";
          ElMessage.error(errMessage);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 导出
const exportLoading = ref(false);
const handleExport = async () => {
  if (exportLoading.value) return;
  exportLoading.value = true;
  try {
    const params: any = {};

    // 传递查询条件
    if (searchForm.returnMaterialCode) {
      params.ReturnMaterialCode = searchForm.returnMaterialCode.trim();
    }

    if (searchForm.materialKeyword) {
      params.MaterialKeyword = searchForm.materialKeyword.trim();
    }

    if (searchForm.workOrderName) {
      params.WorkOrderName = searchForm.workOrderName.trim();
    }

    if (searchForm.returnMaterialDate) {
      params.ReturnMaterialDate = searchForm.returnMaterialDate;
    }

    if (searchForm.stats !== null && searchForm.stats !== undefined) {
      params.Stats = searchForm.stats;
    }

    const response = await https.Reads.get(
      "/Warehouse/ProduceReturnMaterialExport",
      {
        params,
        responseType: "blob",
      }
    );

    // 检查响应是否为 blob
    if (!response.data || !(response.data instanceof Blob)) {
      throw new Error("导出文件格式错误");
    }

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:T]/g, "")
      .slice(0, 14);
    link.download = `生产退料明细_${timestamp}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    ElMessage.success("导出成功，请留意下载文件");
  } catch (error: any) {
    console.error("导出生产退料失败:", error);
    const errMessage =
      error?.response?.data?.msg ??
      error?.response?.data?.Msg ??
      error?.message ??
      "导出生产退料失败，请稍后重试";
    ElMessage.error(errMessage);
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped>
.return-material-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 面包屑卡片 */
.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.25);
  color: #fff;
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-subtitle {
  margin: 0;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #fff;
}

:deep(.breadcrumb-card .el-breadcrumb) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.breadcrumb-card .el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
}

:deep(.breadcrumb-card .el-breadcrumb__separator) {
  color: rgba(255, 255, 255, 0.7);
}

/* 搜索卡片 */
.search-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.search-card__header {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f2f5;
}

.search-card__header h3 {
  margin: 0;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.search-card__header span {
  font-size: 13px;
  color: #909399;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

.search-input {
  width: 260px;
  transition: all 0.3s ease;
}

.search-input:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.search-input:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(102, 126, 234, 0.3) inset;
}

.search-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.search-actions .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-actions .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.search-actions .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.search-actions .el-button:not(.el-button--primary):hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-input {
    width: 100%;
  }

  .search-actions {
    margin-left: 0;
    width: 100%;
  }
}

/* 表格卡片 */
.table-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
  transition: all 0.3s ease;
  overflow: hidden;
}

.table-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.table-header__info {
  flex: 1;
}

.table-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-title-icon {
  font-size: 22px;
  color: #667eea;
}

.table-subtitle {
  margin: 4px 0 8px 0;
  color: #909399;
  font-size: 14px;
}

.table-subtitle strong {
  color: #667eea;
  font-weight: 600;
  margin: 0 2px;
}

.selection-tag {
  margin-top: 8px;
  border-radius: 6px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.table-header__actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.action-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn:active:not(:disabled) {
  transform: translateY(0);
}

.add-btn {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  border: none;
  color: #fff;
}

.batch-delete-btn {
  background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
  border: none;
  color: #fff;
}

.export-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: #fff;
}

/* 现代化表格样式 */
.modern-table {
  border-radius: 8px;
  overflow: hidden;
}

.modern-table :deep(.el-table__header) {
  background: linear-gradient(
    135deg,
    rgba(102, 126, 234, 0.08),
    rgba(118, 75, 162, 0.04)
  );
}

.modern-table :deep(.el-table__header th) {
  background: transparent;
  color: #303133;
  font-weight: 600;
  border-bottom: 2px solid rgba(102, 126, 234, 0.2);
  padding: 16px 0;
}

.modern-table :deep(.el-table__body tr) {
  transition: all 0.3s ease;
}

.modern-table :deep(.el-table__body tr:hover) {
  background: linear-gradient(
    90deg,
    rgba(102, 126, 234, 0.06),
    rgba(102, 126, 234, 0.02)
  ) !important;
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.modern-table :deep(.el-table__body td) {
  padding: 18px 0;
  border-bottom: 1px solid rgba(102, 126, 234, 0.08);
}

.modern-table
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped) {
  background: rgba(102, 126, 234, 0.02);
}

.modern-table
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped:hover) {
  background: linear-gradient(
    90deg,
    rgba(102, 126, 234, 0.08),
    rgba(102, 126, 234, 0.04)
  ) !important;
}

.modern-table :deep(.el-link) {
  font-weight: 500;
  transition: all 0.3s ease;
}

.modern-table :deep(.el-link:hover) {
  color: #667eea !important;
  transform: translateX(2px);
}

.table-code {
  font-weight: 500;
  font-family: "Courier New", monospace;
  color: #606266;
  background: rgba(102, 126, 234, 0.05);
  padding: 4px 10px;
  border-radius: 4px;
  display: inline-block;
}

.table-date {
  color: #606266;
  font-size: 13px;
}

.status-tag {
  min-width: 86px;
  justify-content: center;
  font-weight: 500;
}

/* 表格操作按钮 */
.table-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.table-action-btn {
  transition: all 0.3s ease;
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
}

.table-action-btn:hover {
  transform: scale(1.1);
}

.return-btn:hover {
  color: #67c23a !important;
  background-color: rgba(103, 194, 58, 0.1);
}

.edit-btn:hover {
  color: #409eff !important;
  background-color: rgba(64, 158, 255, 0.1);
}

.delete-btn:hover {
  color: #f56c6c !important;
  background-color: rgba(245, 108, 108, 0.1);
}

/* 空状态 */
.empty-state {
  padding: 60px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #909399;
}

.empty-icon-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(
    135deg,
    rgba(102, 126, 234, 0.1),
    rgba(118, 75, 162, 0.1)
  );
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
}

.empty-icon {
  font-size: 48px;
  color: #c0c4cc;
}

.empty-text {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.empty-hint {
  margin: 0;
  font-size: 13px;
  color: #909399;
  text-align: center;
}

.empty-action-btn {
  margin-top: 8px;
  padding: 10px 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.empty-action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 分页器 */
.table-pagination {
  margin-top: 24px;
  padding: 20px;
  background: linear-gradient(
    135deg,
    rgba(102, 126, 234, 0.03),
    rgba(118, 75, 162, 0.02)
  );
  border-radius: 12px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.pagination-info {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
}

.pagination-info strong {
  color: #667eea;
  font-weight: 600;
  margin: 0 4px;
}

.pagination-text {
  white-space: nowrap;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-btn {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.pagination-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.pagination-component {
  margin: 0 8px;
}

.page-size-select {
  width: 110px;
  border-radius: 6px;
}

.pagination-jumper {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.jump-input {
  width: 70px;
  border-radius: 6px;
}

@media (max-width: 768px) {
  .pagination-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .pagination-controls {
    justify-content: center;
  }
}
</style>
